//
//  ImageManager.m
//  plugin_image
//
//  Created by liting on 2025/8/22.
//

#import "ImageManager.h"
#import "PluginImagePlugin.h"
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>
#import "PermissionManager.h"

@interface ImageManager ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) UIViewController * _Nullable presentController;
@property (nonatomic, copy) FlutterResult result;
@end


@implementation ImageManager

+ (instancetype)sharedInstance {
    static ImageManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}


// 打开相机
- (void)openCamera{
    [[PermissionManager sharedManager] checkPermissionForType:PermissionTypeCamera completion:^(BOOL granted, NSString *message) {
        if (granted) {
            [self getCamera];
        } else if ([message isEqualToString:@"相机未请求授权"]) {
            // 请求授权
            [[PermissionManager sharedManager] requestPermissionForType:PermissionTypeCamera completion:^(BOOL granted, NSString *message) {
                if (granted) {
                    [self getCamera];
                } else {
                    [self createAlertWithStr:message];
                }
            }];
        } else {
            [self createAlertWithStr:message];
        }
    }];
}


-(void)getCamera{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePicker.delegate = self;
        imagePicker.allowsEditing = YES;
        [[self currentActiveController] presentViewController:imagePicker animated:YES completion:nil];
    } else {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Error" message:@"Your device does not have a camera." preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
        [[self currentActiveController] presentViewController:alert animated:YES completion:nil];
    }
}

// 打开相册
- (void)openPhotoAlbum:(FlutterResult)result{
    self.result = result;

    [[PermissionManager sharedManager] checkPermissionForType:PermissionTypePhotoLibrary completion:^(BOOL granted, NSString *message) {
            if (granted) {
                [self getPhotoAlbum];
            } else if ([message isEqualToString:@"相册未请求授权"]) {
                [[PermissionManager sharedManager] requestPermissionForType:PermissionTypePhotoLibrary completion:^(BOOL granted, NSString *message) {
                    if (granted) {
                        [self getPhotoAlbum];
                    } else {
                        [self createAlertWithStr:message];
                    }
                }];
            } else {
                [self createAlertWithStr:message];
            }
        }];

}

- (void)getPhotoAlbum{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.delegate = self;
        imagePicker.allowsEditing = YES;
        [[self currentActiveController] presentViewController:imagePicker animated:YES completion:nil];
    }
}

#pragma mark - UIImagePickerControllerDelegate Methods

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey, id> *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *selectedImage = info[UIImagePickerControllerEditedImage];
    if (!selectedImage) {
        selectedImage = info[UIImagePickerControllerOriginalImage];
    }
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        // 相机
        NSData *imageData = UIImagePNGRepresentation(selectedImage);
        NSDictionary *data = [self createDic:1 andImageData:imageData andMsg:@"成功"];
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([PluginImagePlugin sharedInstance].eventSink != nil) {
                [PluginImagePlugin sharedInstance].eventSink(data);
            } else {
                NSLog(@"⚠️ eventSink is nil, cannot send data");
            }
        });

        } else if (picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
        //相册
        NSData *imageData = UIImagePNGRepresentation(selectedImage);
        NSDictionary *data = [self createDic:1 andImageData:imageData andMsg:@"成功"];
        self.result(data);
    }
    [self.presentController dismissViewControllerAnimated:YES completion:nil];
}


- (NSDictionary *)createDic:(int)code andImageData:(NSData *)imageData andMsg:(NSString*)msg{
    NSMutableDictionary *data = [[NSMutableDictionary alloc]init];
    data[@"code"] = @(code);
    data[@"image"] = imageData;
    data[@"msg"] = msg;
    return data;
}

// 弹窗
- (void)createAlertWithStr:(NSString *)des{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:des preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {}];
    [alert addAction:okAction];
    [[self currentActiveController] presentViewController:alert animated:YES completion:nil];
}

// 获取控制器
- (UIViewController *)currentActiveController {
    UIWindow *window = [UIApplication sharedApplication].delegate.window;
    if (window.windowLevel != UIWindowLevelNormal) {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for (UIWindow * tmpWin in windows) {
            if (tmpWin.windowLevel == UIWindowLevelNormal) {
                window = tmpWin;
                break;
            }
        }
    }
    UIViewController *rootVC = window.rootViewController;
    return rootVC;
}


@end

